import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { UserCreateDTO } from './user.dto'
import { UserEntity } from './user.entity'

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private usersRepository: Repository<UserEntity>
  ) {}

  public async findById(id: number) {
    const data = await this.usersRepository.findOne({ id })

    return data ?? null
  }

  public async findAccount(mobile: string) {
    const user = await this.usersRepository.findOne({ where: { mobile } })

    return user ?? null
  }

  public async findAccountWithPasswd(mobile: string, password: string) {
    const user = await this.usersRepository.findOne({
      where: { mobile, password }
    })

    return user ?? null
  }

  public findAllUser() {
    return this.usersRepository.find()
  }

  public async createUser(data: UserCreateDTO) {
    const result = await this.usersRepository.insert(data)
    return result.identifiers[0]
  }
}
